<template>
  <el-dialog title="新增用户" :visible="visible" @update:visible="visibleHandle" :modal="true">
    <el-form :rules="rule" ref="addUser" label-width="80px" :model="user">
      <el-form-item label="用户名" prop="user">
        <el-input v-model="user.user"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="user.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="psw">
        <el-input v-model="user.psw"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="visibleHandle(false)">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script type="text/javascript">
  export default {
    props: ['visible'],
    data () {
      return {
        user: {
          user: '',
          name: '',
          psw: ''
        },
        rule: {
          user: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          psw: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      visibleHandle (bool) {
        console.log('add-user: ' + bool)
        this.$emit('update:visible', bool)
      },
      save () {
        this.$refs['addUser'].validate((valid) => {
          if (valid) {
            this.$api.call({
              service: 'add-user',
              body: this.user
            }).then((data) => {
              this.$emit('add', true)
              this.$emit('update:visible', false)
            })
          } else {
            return false
          }
        })
      }
    }
  }
</script>